<?php

namespace app\api\model\kuyou\applet;

use app\api\controller\kuyou\applet\Commons;
use app\common\behavior\Common;
use think\Model;
use think\Db;
use Exception;
class Payment extends Model
{

    // 表名
    protected $name = 'kuyou_payment';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 获取列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getList($where,$page,$limit,$type,$sort_field,$sort_type){
        $app_page = config('app_page');
        $app_page = $app_page===false?false:true;
        $pageStatus = true;
        if($app_page){
            if($page<0){
                $pageStatus = false;
            }
        }
        if($pageStatus){
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->order($sort_field,$sort_type)->page($page,$limit)->field("id,purchase_code,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time,
            customers_id,money,write_off,discount,advance,staff_member_id,remarks,preparation_id,examine_id,operation_id,examine_status,print_num,
            FROM_UNIXTIME(examine_time,'%Y-%m-%d') as examine_time")->select())->toArray();
        }else{
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->order($sort_field,$sort_type)->field("id,purchase_code,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time,
            customers_id,money,write_off,discount,advance,staff_member_id,remarks,preparation_id,examine_id,operation_id,examine_status,print_num,
            FROM_UNIXTIME(examine_time,'%Y-%m-%d') as examine_time")->select())->toArray();
        }

        $moneys = 0;$write_off = 0;
        foreach ($list as $list_k=>$list_v){
            $list[$list_k]['customers'] = (new Suppliers())->where(['id'=>$list_v['customers_id']])->value('supplyer_name');
            $list[$list_k]['preparation_name'] = (new User())->where(['id'=>$list_v['preparation_id']])->value('username');
            $list[$list_k]['examine_name'] = (new User())->where(['id'=>$list_v['examine_id']])->value('username');
            $list[$list_k]['staff_member'] = (new StaffMember())->where(['id'=>$list_v['staff_member_id']])->value('name');
            unset($list[$list_k]['preparation_id']);
            unset($list[$list_k]['examine_id']);

            $moneys += $list_v['money'];$write_off += $list_v['write_off'];
            $account = Db::name('kuyou_payment_account')->alias('co')
                ->join('kuyou_accounts a','a.id=co.accounts_id')
                ->join('kuyou_settlementtype s','s.id=co.settlementtype','left')
                ->where(['co.collection_id'=>$list_v['id']])
                ->field('co.money,a.account_name,s.name,co.number,co.remark')
                ->select();
            $list[$list_k]['account_list'] = $account;
        }
        if($type==1){
            $lists = $list;$list=[];
            foreach ($lists as $lists_k=>$lists_v){
                foreach ($lists_v['account_list'] as $k=>$v){
                    unset($lists_v['account_list']);
                    $row = $lists_v;
                    $row['account_money'] = $v['money'];
                    $row['account_account'] = $v['account_name'];
                    $row['account_name'] = $v['name'];
                    $row['account_number'] = $v['number'];
                    $row['account_remark'] = $v['remark'];
                    $list[] = $row;
                }
            }
        }
        $count = self::where(function ($query) use ($where) {
            $query->where($where);
        })->count();
        return ['list'=>$list,'count'=>$count];
    }

    /**
     * 获取详情
     * @param string $purchase_code
     * @return array
     */
    public static function getDetail($purchase_code){
        $detail = self::where(function ($query) use ($purchase_code) {
            $query->where('purchase_code', '=', $purchase_code);
        })->field("id,purchase_code,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time,
            customers_id,money,write_off,discount,advance,staff_member_id,remarks,preparation_id,examine_id,operation_id,examine_status,print_num,
            FROM_UNIXTIME(examine_time,'%Y-%m-%d') as examine_time")->find();
        if($detail){
            $detail['staff_member_name'] = (new StaffMember())->where(['id'=>$detail['staff_member_id']])->value('name');
            $give_account = Db::name('kuyou_suppliers')->where(['id'=>$detail['customers_id']])->field('need_give_account,supplyer_name')->find();
            if($detail['examine_status']==1){
                $detail['give_account'] = $give_account['need_give_account']-$detail['money'];
            }else{
                $detail['give_account'] = $give_account['need_give_account'];
            }
            $detail['customers_name'] = isset($give_account['supplyer_name'])?$give_account['supplyer_name']:'';

            $accounts = new Accounts();$settlementtype = new Settlementtype();
            $account = Db::name('kuyou_payment_account')->where(['collection_id'=>$detail['id']])->select();
            foreach ($account as $account_k=>$account_v){
                $account[$account_k]['purchase_time'] = date('Y-m-d',$account_v['purchase_time']);
                $account[$account_k]['accounts_name'] = $accounts->where(['id'=>$account_v['accounts_id']])->value('account_name');
                $account[$account_k]['settlementtype_name'] = $settlementtype->where(['id'=>$account_v['settlementtype']])->value('name');
                unset($account[$account_k]['id']);unset($account[$account_k]['admin_id']);
            }
            $detail['account_list'] = $account;

            $sale = Db::name('kuyou_payment_sale')->where(['collection_id'=>$detail['id']])->select();
            foreach ($sale as $sale_k=>$sale_v){
                $sale[$sale_k]['purchase_time'] = date('Y-m-d',$sale_v['purchase_time']);
                $sale[$sale_k]['times'] = date('Y-m-d',$sale_v['times']);
                unset($sale[$sale_k]['old_money']);unset($sale[$sale_k]['old_status']);unset($sale[$sale_k]['old_status_i']);unset($sale[$sale_k]['old_money_i']);
                unset($sale[$sale_k]['id']);unset($sale[$sale_k]['admin_id']);
            }
            $detail['sale_list'] = $sale;
        }
        if(!empty($detail)){
            return ['status'=>200,'msg'=>$detail];
        }else{
            return ['status'=>500,'msg'=>'未查询到相关数据'];
        }
    }

    /**
     * 添加
     * @param array $detail
     * @return array
     */
    public static function addDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'purchase_code|单据编号'=>'require',
                'purchase_time|单据时间'=>'require',
                'suppliers_id|供应商'=>'require',
                'staff_member_id|收款人'=>'require|money',
                'account_list|结算信息'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $adminId = (new Commons())->getAdminId();
                if(empty($adminId)){
                    return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
                }
                $status = (new Commons())->checkCode($detail['purchase_code'],22);//验证编号是否合法
                if($status){
                    $examine= (new Commons())->getSet('examine','is_checked');

                    $account_list = (array)json_decode($detail['account_list'], true);
                    $sale_list = isset($detail['sale_list'])?$detail['sale_list']:'';
                    $sale_list = (array)json_decode($sale_list, true);

                    //账户信息
                    $account = [];
                    $account_id = [];
                    foreach ($account_list as $k=>$v){
                        if(!empty($v['accounts_id'])){//有账户
                            $accounts = Db::name('kuyou_accounts')->where(['id'=>$v['accounts_id']])->find();
                            if(empty($accounts)){
                                return ['status'=>500,'msg'=>'账户信息错误'];
                            }
                            if(in_array($v,$account_id)){
                                return ['status'=>500,'msg'=>'不可多次选择相同的结算账户'];
                            }else{
                                $account_id[] = $v;
                            }
                            $account[] = [
                                'purchase_code'    => $detail['purchase_code'],
                                'purchase_time'    => strtotime($detail['purchase_time']),
                                'accounts_id'      => $v['accounts_id'],
                                'money'            => isset($v['money'])?(float)$v['money']:0,
                                'settlementtype'   => isset($v['settlementtype'])?(float)$v['settlementtype']:0,
                                'number'           => isset($v['number'])?$v['number']:0,
                                'remark'           => isset($v['remark'])?$v['remark']:'',
                            ];
                        }
                    }
                    $account_money = 0;//账户收支总金额
                    foreach ($account as $account_k=>$account_v){
                        $account_money += $account_v['money'];
                    }
                    //账户信息结束

                    //源单信息
                    $sale = [];
                    $sale_id = [];
                    $log_arr = [];
                    $log_add = [];
                    foreach ($sale_list as $k=>$v){
                        if(!empty($v['purchase_number']) && !empty($v['purchase_type'])){//有单号
                            $order = Db::name('kuyou_writeoff_source')->where(['id'=>$v['purchase_type']])->find();
                            if(empty($order)){
                                return ['status'=>500,'msg'=>'源单信息查询错误'];
                            }
                            if(in_array($v,$sale_id)){
                                return ['status'=>500,'msg'=>'不可多次选择相同的源单'];
                            }else{
                                $sale_id[] = $v;
                            }
                            $thisrow = [
                                'purchase_code'    => $detail['purchase_code'],
                                'purchase_time'    => strtotime($detail['purchase_time']),
                                'purchase_number'  => $order['purchase_code'],
                                'business_name'    => isset($v['business_type'])?$v['business_type']:null,
                                'business_type'    => $order['purchase_type'],
                                'times'            => $order['purchase_time'],
                                'money'            => $order['price'],
                                'write_off'        => isset($v['write_off'])?(float)$v['write_off']:0,
                                'write_off_money'  => isset($v['write_off_money'])?(float)$v['write_off_money']:0,
                                'write_off_price'  => isset($v['write_off_price'])?(float)$v['write_off_price']:0,
                                'remark'           => $order['remark'],
                                'source_id'        => $order['id'],
                                'type'             => $order['type'],
                            ];
                            $sale[] = $thisrow;

                            $where = [];
                            $where['source_id'] = $order['id'];
                            $log = Db::name('kuyou_writeoff_log')->where($where)->find();
                            if($log){
                                $status = true;
                                foreach ($log_arr as $log_arr_k=>$log_arr_v){
                                    if($log_arr_v['id']==$log['id']){
                                        $status = false;
                                        $log_arr[$log_arr_k]['money'] += $thisrow['write_off_price'];
                                        $log_arr[$log_arr_k]['write_off'] -= $thisrow['write_off_price'];
                                    }
                                }
                                if($status){
                                    $log_arr[] = [
                                        'id' => $log['id'],
                                        'write_off' => $log['write_off']-$thisrow['write_off_price'],
                                        'money' => $log['money']+$thisrow['write_off_price'],
                                    ];
                                }
                            }else{
                                $log_add[] = [
                                    'source_id' => $order['id'],
                                    'write_off' => $thisrow['write_off_money']-$thisrow['write_off_price'],
                                    'money' => $thisrow['write_off_price'],
                                ];
                            }
                        }
                    }
                    $sale_money = 0;//账户收支总金额
                    foreach ($sale as $sale_k=>$sale_v){
                        $sale_money += $sale_v['write_off_price'];
                    }
                    $business_type = !empty($sale)?2:1;
                    $rowdata = [
                        'purchase_code'     =>  $detail['purchase_code'],
                        'purchase_time'     =>  strtotime($detail['purchase_time']),
                        'business_type'     =>  $business_type,
                        'customers_id'      =>  $detail['suppliers_id'],
                        'money'             =>  $account_money,
                        'write_off'         =>  $sale_money,
                        'discount'          =>  isset($detail['discount'])?(float)$detail['discount']:0,
                        'advance'           =>  isset($detail['advance'])?(float)$detail['advance']:0,
                        'staff_member_id'   =>  isset($detail['staff_member_id'])?(float)$detail['staff_member_id']:null,
                        'remarks'           =>  $detail['note'],
                        'preparation_id'    =>  $adminId,
                        'operation_id'      =>  $adminId,
                        'createtime'        => time(),
                        'updatetime'        => time(),
                    ];

                    if(empty($account)){
                        return ['status'=>500,'msg'=>'请填写账户结算信息'];
                    }


                    $model = new Payment();
                    $row = $model->where(['purchase_code'=>$detail['purchase_code']])->value('id');
                    if($row){
                        return ['status'=>500,'msg'=>'单据编号已使用，请重新输入单据编号'];
                    }
                    $result = false;
                    Db::startTrans();
                    try {
                        $model->allowField(true)->save($rowdata);
                        $result = $model->id;

                        foreach ($account as $account_k=>$account_v){
                            $account[$account_k]['collection_id'] = $result;
                        }
                        Db::name('kuyou_payment_account')->insertAll($account);

                        foreach ($sale as $sale_k=>$sale_v){
                            $sale[$sale_k]['collection_id'] = $result;
                        }
                        Db::name('kuyou_payment_sale')->insertAll($sale);
                        if(!empty($log_arr)){
                            (new WriteoffLog())->saveAll($log_arr);
                        }
                        if(!empty($log_add)){
                            (new WriteoffLog())->insertAll($log_add);
                        }
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        return ['status'=>500,'msg'=>$e->getMessage()];
                    }
                    if($result){
                        if($examine!=1){
                            try {
                                $exa = self::examine($detail['purchase_code']);
                            } catch (Exception $e) {
                            }
                            if(!isset($exa['status']) || (isset($exa['status']) && $exa['status']!=1)){
                                try {
                                    self::delDetail($detail['purchase_code']);
                                } catch (Exception $e) {
                                }
                                return ['status'=>500,'msg'=>$exa['msg']];
                            }
                        }
                        return ['status'=>200,'msg'=>$detail['purchase_code']];
                    }else{
                        return ['status'=>500,'msg'=>'添加失败'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'编号规则错误'];
                }
            }
        }
    }

    /**
     * 更新
     * @param array $detail
     * @return array
     */
    public static function editDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'old_purchase_code|原单据编号'=>'require',
                'purchase_code|单据编号'=>'require',
                'purchase_time|单据时间'=>'require',
                'suppliers_id|供应商'=>'require',
                'staff_member_id|收款人'=>'require|money',
                'account_list|结算信息'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $adminId = (new Commons())->getAdminId();
                if(empty($adminId)){
                    return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
                }
                $status = (new Commons())->checkCode($detail['purchase_code'],22);//验证编号是否合法
                if($status){
                    $model = new Payment();
                    $row = $model->where(['purchase_code'=>$detail['old_purchase_code']])->find();
                    if(empty($row)){
                        return ['status'=>500,'msg'=>'修改的单据不存在'];
                    }
                    $old_purchase_code = $detail['old_purchase_code'];
                    $examine= (new Commons())->getSet('examine','is_checked');

                    $account_list = (array)json_decode($detail['account_list'], true);
                    $sale_list = isset($detail['sale_list'])?$detail['sale_list']:'';
                    $sale_list = (array)json_decode($sale_list, true);

                    //账户信息
                    $account = [];
                    $account_id = [];
                    foreach ($account_list as $k=>$v){
                        if(!empty($v['accounts_id'])){//有账户
                            $accounts = Db::name('kuyou_accounts')->where(['id'=>$v['accounts_id']])->find();
                            if(empty($accounts)){
                                return ['status'=>500,'msg'=>'账户信息错误'];
                            }
                            if(in_array($v,$account_id)){
                                return ['status'=>500,'msg'=>'不可多次选择相同的结算账户'];
                            }else{
                                $account_id[] = $v;
                            }
                            $account[] = [
                                'purchase_code'    => $detail['purchase_code'],
                                'purchase_time'    => strtotime($detail['purchase_time']),
                                'collection_id'    => $row['id'],
                                'accounts_id'      => $v['accounts_id'],
                                'money'            => isset($v['money'])?(float)$v['money']:0,
                                'settlementtype'   => isset($v['settlementtype'])?(float)$v['settlementtype']:0,
                                'number'           => isset($v['number'])?$v['number']:0,
                                'remark'           => isset($v['remark'])?$v['remark']:'',
                            ];
                        }
                    }
                    $account_money = 0;//账户收支总金额
                    foreach ($account as $account_k=>$account_v){
                        $account_money += $account_v['money'];
                    }
                    //账户信息结束

                    //源单信息
                    $sale = [];
                    $sale_id = [];
                    $log_arr = [];
                    $log_add = [];
                    foreach ($sale_list as $k=>$v){
                        if(!empty($v['purchase_number']) && !empty($v['purchase_type'])){//有单号
                            $order = Db::name('kuyou_writeoff_source')->where(['id'=>$v['purchase_type']])->find();
                            if(empty($order)){
                                return ['status'=>500,'msg'=>'源单信息查询错误'];
                            }
                            if(in_array($v,$sale_id)){
                                return ['status'=>500,'msg'=>'不可多次选择相同的源单'];
                            }else{
                                $sale_id[] = $v;
                            }
                            $thisrow = [
                                'purchase_code'    => $detail['purchase_code'],
                                'purchase_time'    => strtotime($detail['purchase_time']),
                                'purchase_number'  => $order['purchase_code'],
                                'collection_id'    => $row['id'],
                                'business_name'    => isset($v['business_type'])?$v['business_type']:null,
                                'business_type'    => $order['purchase_type'],
                                'times'            => $order['purchase_time'],
                                'money'            => $order['price'],
                                'write_off'        => isset($v['write_off'])?(float)$v['write_off']:0,
                                'write_off_money'  => isset($v['write_off_money'])?(float)$v['write_off_money']:0,
                                'write_off_price'  => isset($v['write_off_price'])?(float)$v['write_off_price']:0,
                                'remark'           => $order['remark'],
                                'source_id'        => $order['id'],
                                'type'             => $order['type'],
                            ];
                            $sale[] = $thisrow;

                            $where = [];
                            $where['source_id'] = $order['id'];
                            $log = Db::name('kuyou_writeoff_log')->where($where)->find();
                            if($log){
                                $status = true;
                                foreach ($log_arr as $log_arr_k=>$log_arr_v){
                                    if($log_arr_v['id']==$log['id']){
                                        $status = false;
                                        $log_arr[$log_arr_k]['money'] += $thisrow['write_off_price'];
                                        $log_arr[$log_arr_k]['write_off'] -= $thisrow['write_off_price'];
                                    }
                                }
                                if($status){
                                    $log_arr[] = [
                                        'id' => $log['id'],
                                        'write_off' => $log['write_off']-$thisrow['write_off_price'],
                                        'money' => $log['money']+$thisrow['write_off_price'],
                                    ];
                                }
                            }else{
                                $log_add[] = [
                                    'source_id' => $order['id'],
                                    'write_off' => $thisrow['write_off_money']-$thisrow['write_off_price'],
                                    'money' => $thisrow['write_off_price'],
                                ];
                            }
                        }
                    }
                    $sale_money = 0;//账户收支总金额
                    foreach ($sale as $sale_k=>$sale_v){
                        $sale_money += $sale_v['write_off_price'];
                    }
                    $business_type = !empty($sale)?2:1;
                    $rowdata = [
                        'purchase_code'     =>  $detail['purchase_code'],
                        'purchase_time'     =>  strtotime($detail['purchase_time']),
                        'business_type'     => $business_type,
                        'customers_id'      =>  $detail['suppliers_id'],
                        'money'             =>  $account_money,
                        'write_off'         =>  $sale_money,
                        'discount'          =>  isset($detail['discount'])?(float)$detail['discount']:0,
                        'advance'           =>  isset($detail['advance'])?(float)$detail['advance']:0,
                        'staff_member_id'   =>  isset($detail['staff_member_id'])?(float)$detail['staff_member_id']:null,
                        'remarks'           =>  $detail['note'],
                        'preparation_id'    =>  $adminId,
                        'operation_id'      =>  $adminId,
                        'updatetime'        => time(),
                    ];

                    if(empty($account)){
                        return ['status'=>500,'msg'=>'请填写账户结算信息'];
                    }

                    if($detail['purchase_code']!=$detail['old_purchase_code']){
                        $purchase_id = $model->where(['purchase_code'=>$detail['purchase_code']])->value('id');
                        if($purchase_id){
                            return ['status'=>500,'msg'=>'单据编号已使用，请重新输入单据编号'];
                        }
                    }

                    //详情
                    $info_list = Db::name('kuyou_writeoff_info')->where(['collection_id'=>$row['id']])->select();
                    $writeoff_log = [];
                    foreach ($info_list as $info_list_k=>$info_list_v){
                        $log = Db::name('kuyou_writeoff_log')->where(['source_id'=>$info_list_v['source_id']])->find();
                        if($log){
                            $addstatus = true;
                            foreach ($writeoff_log as $writeoff_log_k=>$writeoff_log_v){
                                if($writeoff_log_v['id']==$log['id']){
                                    $addstatus = false;
                                    $writeoff_log[$writeoff_log_k]['write_off'] = $writeoff_log_v['write_off']+$info_list_v['write_off_price'];
                                    $writeoff_log[$writeoff_log_k]['money'] = $writeoff_log_v['money']-$info_list_v['money'];
                                }
                            }
                            if($addstatus){
                                $writeoff_log[] = [
                                    'id' => $log['id'],
                                    'write_off'=>($log['write_off']+$info_list_v['write_off_price']),
                                    'money'=>($log['money']-$info_list_v['write_off_price'])
                                ];
                            }
                        }
                    }
                    foreach ($log_arr as $log_arr_k=>$log_arr_v){
                        $log = Db::name('kuyou_writeoff_log')->where(['id'=>$log_arr_v['id']])->find();
                        if($log){
                            $addstatus = true;
                            foreach ($writeoff_log as $writeoff_log_k=>$writeoff_log_v){
                                if($writeoff_log_v['id']==$log['id']){
                                    $addstatus = false;
                                    $writeoff_log[$writeoff_log_k]['write_off'] = $writeoff_log_v['write_off']-$log_arr_v['write_off'];
                                    $writeoff_log[$writeoff_log_k]['money'] = $writeoff_log_v['money']+$log_arr_v['money'];
                                }
                            }
                            if($addstatus){
                                $writeoff_log[] = [
                                    'id' => $log['id'],
                                    'write_off'=>($log['write_off']-$log_arr_v['write_off']),
                                    'money'=>($log['money']+$log_arr_v['write_off'])
                                ];
                            }
                        }
                    }

                    if($row){
                        $res = false;
                        Db::startTrans();
                        try {
                            if($examine!=1 && $row['examine_status']==1){
                                self::examinef($detail['old_purchase_code']);
                            }
                            $rowdata['updatetime'] = time();
                            $res = $model->where(['purchase_code'=>$detail['old_purchase_code']])->update($rowdata);
                            if(!empty($info_id)){
                                Db::name('kuyou_goods_purord_info')->where(['purchase_id'=>['in',$info_id]])->delete();
                            }
                            Db::name('kuyou_payment_account')->where(['collection_id'=>$row['id']])->delete();
                            Db::name('kuyou_payment_sale')->where(['collection_id'=>$row['id']])->delete();

                            Db::name('kuyou_payment_account')->insertAll($account);
                            Db::name('kuyou_payment_sale')->insertAll($sale);
                            if(!empty($log_add)){
                                (new WriteoffLog())->insertAll($log_add);
                            }
                            if(!empty($writeoff_log)){
                                (new WriteoffLog())->saveAll($writeoff_log);
                            }
                            Db::commit();
                        } catch (Exception $e) {
                            Db::rollback();
                            return ['status'=>500,'msg'=>$e->getMessage()];
                        }
                        if($res){
                            if($examine!=1){
                                try {
                                    $exa = self::examine($detail['purchase_code']);
                                } catch (Exception $e) {
                                }
                                if(!isset($exa['status']) || (isset($exa['status']) && $exa['status']!=1)){
                                    return ['status'=>500,'msg'=>$exa['msg']];
                                }
                            }
                            return ['status'=>200,'msg'=>'更新成功'];
                        }else{
                            return ['status'=>500,'msg'=>'更新失败'];
                        }
                    }else{
                        return ['status'=>500,'msg'=>'未查询到可更新数据'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'编号规则错误'];
                }
            }
        }
    }

    /**
     * 删除
     * @param string $purchase_code
     * @return array
     */
    public static function delDetail($purchase_code){
        if(empty($purchase_code)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $purchase_code = explode(',',$purchase_code);
            $model = new Payment();
            $examine= (new Commons())->getSet('examine','is_checked');

            $list = $model->where(['purchase_code'=>['in',$purchase_code]])->select();
            $del_id = [];
            foreach ($list as $list_k=>$list_v){
                if($list_v['examine_status']==1 && $examine==1){
                    return ['status'=>500,'msg'=>'不能删除已审核的数据'];
                }else{
                    $del_id[] = $list_v['id'];
                }
            }
            $info_list = Db::name('kuyou_payment_sale')->where(['collection_id'=>['in',$del_id]])->select();
            $count = 0;
            $res = false;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    if ($v['examine_status']==1 && $examine!=1){
                        try {
                            self::examinef($v['purchase_code']);
                        } catch (Exception $e) {
                        }
                    }
                    $res = $model->where(['purchase_code'=>$v['purchase_code']])->delete();
                    $count += $res;
                }
                foreach ($info_list as $info_list_k=>$info_list_v){
                    $log = Db::name('kuyou_writeoff_log')->where(['source_id'=>$info_list_v['source_id']])->find();
                    if($log){
                        Db::name('kuyou_writeoff_log')->where(['id'=>$log['id']])->update([
                            'write_off'=>($log['write_off']+$info_list_v['write_off_price']),
                            'money'=>($log['money']-$info_list_v['write_off_price'])
                        ]);
                    }
                }
                Db::name('kuyou_payment_account')->where(['collection_id'=>['in',$del_id]])->delete();
                Db::name('kuyou_payment_sale')->where(['collection_id'=>['in',$del_id]])->delete();
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return ['status'=>500,'msg'=>$e->getMessage()];
            }
            if($res){
                return ['status'=>200,'msg'=>$count];
            }else{
                return ['status'=>500,'msg'=>'删除失败'];
            }
        }
    }

    /**
     * 审核
     * @param array $purchase_code
     * @return array
     */
    public static function examine($purchase_code = null){
        if(empty($purchase_code)){
            return ['status'=>400,'msg'=>'请选择要操作的数据'];
        }
        $adminId = (new Commons())->getAdminId();
        if(empty($adminId)){
            return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
        }
        $model = new Payment();
        $list = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'0'])->select();
        if(empty($list)){
            return ['status'=>500,'msg'=>'请选择需要审核的数据'];
        }

        $success_count = 0;
        foreach ($list as $list_k=>$list_v){
            //账户信息
            $accountData = [];$log = [];
            $account = Db::name('kuyou_payment_account')->where(['collection_id'=>$list_v['id']])->select();
            foreach ($account as $account_k=>$account_v){
                $accounts = Db::name('kuyou_accounts')->where(['id'=>$account_v['accounts_id']])->find();
                $log[] = [
                    'account_coding'    => $accounts['account_coding'],
                    'account_name'      => $accounts['account_name'],
                    'balance'           => $accounts['balance']+$account_v['money'],
                    'expenditure'       => $account_v['money'],
                    'pay_time'          => time(),
                    'bill_code'         => $account_v['purchase_code'],
                    'business_type'     => '8',
                    'customers_id'      => $list_v['customers_id'],
                    'payment'           => $list_v['staff_member_id'],
                    'remark'            => $list_v['remarks'],
                    'createtime'        => time(),
                    'updatetime'        => time(),
                ];
                $accountData[] = [
                    'balance'  => $account_v['money'],
                    'account'  => $accounts['id'],
                ];
            }
            //账户信息结束
            //客户对账单
            $accounts_receivable = [];
            if(!empty($list_v['customers_id'])){
                $accounts_receivable[] = [
                    'suppliers_id'      => $list_v['customers_id'],
                    'purchase_time'     => $list_v['purchase_time'],
                    'purchase_code'     => $list_v['purchase_code'],
                    'business_type'     => '9',
                    'receivable'        => -$list_v['money'],
                    'remark'            => $list_v['remarks'],
                    'real_money'        => $list_v['money'],
                    'createtime'        => time(),
                    'updatetime'        => time(),
                ];
            }
            $info_list = Db::name('kuyou_payment_sale')->where(['collection_id'=>$list_v['id']])->select();
            $suppliers = Db::name('kuyou_suppliers')->where(['id'=>$list_v['customers_id']])->find();
            $gave_money = $suppliers['need_give_account'] - $list_v['money'];
            foreach ($info_list as $info_list_k=>$info_list_v){
                if($info_list_v['business_type']==4 && $info_list_v['type']==1){
                    //普通购货
                    $order = Db::name('kuyou_goods_purchase')->where(['purchase_code'=>$info_list_v['purchase_number']])->find();
                    if($order){
                        $all_money = $order['all_money']+$order['tax_money'];
                        $pay_money = $order['pay_money']+$info_list_v['write_off_price'];
                        if($all_money<$pay_money){
                            return ['status'=>500,'msg'=>$info_list_v['purchase_number'].'核销金额不能大于未核销金额'];
                        }
                    }
                }else if($info_list_v['business_type']==4 && $info_list_v['type']==2){
                    //购货退货
                    $order = Db::name('kuyou_goods_exchange')->where(['purchase_code'=>$info_list_v['purchase_number']])->find();
                    if($order){
                        $all_money = $order['all_money']+$order['tax_money'];
                        $pay_money = $order['retreat_money']+(-$info_list_v['write_off_price']);
                        if($all_money<$pay_money){
                            return ['status'=>500,'msg'=>$info_list_v['purchase_number'].'核销金额不能大于未核销金额'];
                        }
                    }
                }
            }
            Db::startTrans();
            try {
                if(!empty($accounts_receivable)){
                    Db::name('kuyou_accounts_copewith')->insertAll($accounts_receivable);
                }
                if($list_v['business_type']==1){
                    Db::name('kuyou_writeoff_source')->insert([
                        'purchase_type' => 2,
                        'type' => 1,
                        'suppliers_code' => $suppliers['supplyer_code'],
                        'purchase_code' => $list_v['purchase_code'],
                        'purchase_time' => $list_v['purchase_time'],
                        'price' => $list_v['advance'],
                        'money' => 0,
                        'write_off' => $list_v['advance'],
                        'remark' => $list_v['remarks'],
                    ]);
                }

                foreach ($info_list as $info_list_k=>$info_list_v){
                    $income = Db::name('kuyou_invoicing')->where(['bill_code'=>$info_list_v['purchase_number']])->find();
                    if($info_list_v['business_type']==4 && $info_list_v['type']==1){
                        //普通购货
                        $order = Db::name('kuyou_goods_purchase')->where(['purchase_code'=>$info_list_v['purchase_number']])->find();
                        if($order){
                            Db::name('kuyou_payment_log')->insert([
                                'suppliers_code' => $order['supplyer_code'],
                                'business_type'  => '3',
                                'bill_time'      => time(),
                                'bill_code'      => $order['purchase_code'],
                                'bill_codes'     => $info_list_v['purchase_code'],
                                //'pay_money'      => $order['preferential_money']+$order['real_money'],
                                'pay_money'      => $info_list_v['write_off_price'],
                                'reamrk'         => $list_v['remarks'],
                                'createtime'     => time(),
                            ]);
                            $more_money = $order['all_money']+$order['tax_money']-$info_list_v['write_off_price']-$order['pay_money'];
                            $status = $more_money<=0?1:2;
                            $pay_money = $order['pay_money']+$info_list_v['write_off_price'];
                            Db::name('kuyou_goods_purchase')->where(['purchase_code'=>$info_list_v['purchase_number']])
                                ->update(['pay_money'=>$pay_money,'pay_status'=>$status]);
                            Db::name('kuyou_payment_sale')->where(['id'=>$info_list_v['id']])->update([
                                'old_money'=>$order['pay_money'],
                                'old_status'=>$order['pay_status'],
                                'old_status_i'=>$income['status']
                            ]);
                            if($income){
                                Db::name('kuyou_invoicing')->where(['bill_code'=>$info_list_v['purchase_number']])
                                    ->update(['status'=>$status]);
                            }
                        }
                    }
                    if($info_list_v['business_type']==4 && $info_list_v['type']==2){
                        //购货退货
                        $order = Db::name('kuyou_goods_exchange')->where(['purchase_code'=>$info_list_v['purchase_number']])->find();
                        Db::name('kuyou_payment_log')->insert([
                            'suppliers_code' => $order['supplyer_code'],
                            'business_type'  => '4',
                            'bill_time'      => time(),
                            'bill_code'      => $order['purchase_code'],
                            'bill_codes'     => $info_list_v['purchase_code'],
                            //'pay_money'      => $order['preferential_money']+$order['real_money'],
                            'pay_money'      => $info_list_v['write_off_price'],
                            'reamrk'         => $list_v['remarks'],
                            'createtime'     => time(),
                        ]);
                        if($order){
                            $more_money = $order['all_money']+$order['tax_money']+$info_list_v['write_off_price']-$order['retreat_money'];;
                            $status = $more_money==0?1:2;
                            $pay_money = $order['retreat_money']+(-$info_list_v['write_off_price']);
                            Db::name('kuyou_goods_exchange')->where(['purchase_code'=>$info_list_v['purchase_number']])
                                ->update(['retreat_money'=>$pay_money,'retreat_status'=>$status]);
                            Db::name('kuyou_payment_sale')->where(['id'=>$info_list_v['id']])->update([
                                'old_money'=>$order['retreat_money'],
                                'old_status'=>$order['retreat_status'],
                                'old_status_i'=>$income['status']
                            ]);
                        }
                        if($income){
                            $status += 3;
                            Db::name('kuyou_invoicing')->where(['bill_code'=>$info_list_v['purchase_number']])
                                ->update(['status'=>$status]);
                        }
                    }
                }

                foreach ($accountData as $accountData_k=>$accountData_v){
                    if($accountData_v['balance']<0){
                        $accountData_v['balance'] = -$accountData_v['balance'];
                    }
                    Db::name('kuyou_accounts')->where(['id'=>$accountData_v['account']])->dec('balance',$accountData_v['balance'])->update();
                }
                if(!empty($log)){
                    Db::name('kuyou_accounts_log')->insertAll($log);
                }

                Db::name('kuyou_suppliers')->where(['id'=>$list_v['customers_id']])->update(['need_give_account'=>$gave_money]);
                $result = $model->where(['id'=>$list_v['id'],'examine_status'=>'0'])->update(['examine_status'=>1,'examine_id'=>$adminId,'examine_time'=>time(),'operation_id'=>$adminId]);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return ['status'=>500,'msg'=>$e->getMessage()];
            }
            if(isset($result) && $result !== false){
                $success_count += 1;
            }
        }

        if($success_count>0){
            return ['status'=>1,'msg'=>$success_count];
        }else{
            return ['status'=>500,'msg'=>'审核失败'];
        }
    }

    /**
     * 反审核
     * @param array $purchase_code
     * @return array
     */
    public static function examinef($purchase_code = null){
        if(empty($purchase_code)){
            return ['status'=>400,'msg'=>'请选择要操作的数据'];
        }
        $adminId = (new Commons())->getAdminId();
        if(empty($adminId)){
            return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
        }

        $model = new Payment();
        $list = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'1'])->select();
        if(empty($list)){
            return ['status'=>500,'msg'=>'请选择需要反审核的数据'];
        }

        $success_count = 0;
        foreach ($list as $list_k=>$list_v){
            //账户信息
            $accountData = [];$log = [];
            $account = Db::name('kuyou_payment_account')->where(['collection_id'=>$list_v['id']])->select();
            foreach ($account as $account_k=>$account_v){
                $accounts = Db::name('kuyou_accounts')->where(['id'=>$account_v['accounts_id']])->find();
                $accountData[] = [
                    'balance'  => $account_v['money'],
                    'account'  => $accounts['id'],
                ];
                $log[] = $account_v['purchase_code'];
            }

            $info_list = Db::name('kuyou_payment_sale')->where(['collection_id'=>$list_v['id']])->select();
            $suppliers = Db::name('kuyou_suppliers')->where(['id'=>$list_v['customers_id']])->find();
            $gave_money = $suppliers['need_give_account'] + $list_v['money'];
            //账户信息结束
            Db::startTrans();
            try {
                Db::name('kuyou_writeoff_source')->where(['purchase_code'=>$list_v['purchase_code'],'purchase_type'=>'2','type'=>'1'])->delete();
                foreach ($info_list as $info_list_k=>$info_list_v){
                    if($info_list_v['business_type']==4 && $info_list_v['type']==1){
                        //普通购货
                        $order = Db::name('kuyou_goods_purchase')->where(['purchase_code'=>$info_list_v['purchase_number']])->find();
                        if($order){
                            Db::name('kuyou_goods_purchase')->where(['purchase_code'=>$info_list_v['purchase_number']])
                                ->update(['pay_money'=>$info_list_v['old_money'],'pay_status'=>$info_list_v['old_status']]);
                        }
                    }
                    if($info_list_v['business_type']==4 && $info_list_v['type']==2){
                        //购货退货
                        $order = Db::name('kuyou_goods_exchange')->where(['purchase_code'=>$info_list_v['purchase_number']])->find();
                        if($order){
                            Db::name('kuyou_goods_exchange')->where(['purchase_code'=>$info_list_v['purchase_number']])
                                ->update(['retreat_money'=>$info_list_v['old_money'],'retreat_status'=>$info_list_v['old_status']]);
                        }
                    }
                    $income = Db::name('kuyou_invoicing')->where(['bill_code'=>$info_list_v['purchase_number']])->find();
                    if($income){
                        if($info_list_v['business_type']==4 && $info_list_v['type']==2){
                            $info_list_v['old_status'] += 3;
                        }
                        Db::name('kuyou_invoicing')->where(['bill_code'=>$info_list_v['purchase_number']])
                            ->update(['status'=>$info_list_v['old_status']]);
                    }
                    Db::name('kuyou_payment_log')->where(['bill_codes'=>$info_list_v['purchase_code']])->delete();
                }
                foreach ($accountData as $accountData_k=>$accountData_v){
                    if($accountData_v['balance']<0){
                        $accountData_v['balance'] = -$accountData_v['balance'];
                    }
                    Db::name('kuyou_accounts')->where(['id'=>$accountData_v['account']])->inc('balance',$accountData_v['balance'])->update();
                }
                if(!empty($log)){
                    Db::name('kuyou_accounts_log')->where(['bill_code'=>['in',$log],'business_type'=>'8'])->delete();
                }

                Db::name('kuyou_suppliers')->where(['id'=>$list_v['customers_id']])->update(['need_give_account'=>$gave_money]);
                $result = $model->where(['id'=>$list_v['id'],'examine_status'=>'1'])->update(['examine_status'=>'0','examine_id'=>null,'examine_time'=>null,'operation_id'=>$adminId]);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return ['status'=>500,'msg'=>$e->getMessage()];
            }
            if(isset($result) && $result !== false){
                $success_count += 1;
            }
        }
        if($success_count>0){
            return ['status'=>1,'msg'=>$success_count];
        }else{
            return ['status'=>500,'msg'=>'反审核失败'];
        }
    }

}
